package com.codefish.codefishseckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codefish.codefishseckill.entity.Order;
import com.codefish.codefishseckill.mapper.OrderMapper;
import com.codefish.codefishseckill.service.OrderService;
import com.codefish.codefishseckill.service.SecKillGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author codefish
 * @since 2022-07-07
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;


    @Override
    public List<Order> selectOrderByCondition(Long userId, Long goodsId) {
        if (userId == null) {
            throw new IllegalArgumentException("下单用户id不能为空");
        }
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        if (goodsId != null) {
            wrapper.eq("goods_id", goodsId);
        }
        return super.list(wrapper);
    }

    @Override
    public Long getOneByCondition(Long userId, Long goodsId) {
        Integer stock = (Integer) redisTemplate.opsForValue().get(SecKillGoodsService.SECKILL_GOODS_STOCK_PREFIX + goodsId);
        if (stock == null || stock <= 0) {
            return -1L;
        }
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.select("order_id").eq("user_id", userId).eq("goods_id", goodsId);
        Order order = super.getOne(wrapper);

        return order == null ? 0L : order.getOrderId();
    }


    @Override
    public Order getOrderByOrderId(Long orderId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        return super.getOne(wrapper);
    }
}
